package cn.szzsi._web;

import cn.szzsi._Config;
import cn.szzsi.common.bean.CartItemCookie;
import cn.szzsi.common.bean.SystemConfig;
import cn.szzsi.common.bean.SystemConfig.PointType;
import cn.szzsi.common.bean.SystemConfig.StoreFreezeTime;
import cn.szzsi.common.bean.WeixinConfig;
import cn.szzsi.common.bean.dto.Msg;
import cn.szzsi.common.exception.BusinessException;
import cn.szzsi.common.kit.*;
import cn.szzsi.common.kuaidi.KdApiOrderDistinguish;
import cn.szzsi.common.model.*;
import cn.szzsi.common.model.OrderLog.OrderLogType;
import cn.szzsi.common.model.Payment.PaymentType;
import cn.szzsi.common.model.Product.WeightUnit;
import cn.szzsi.common.model.zshop.BusinessBalanceDetailService;
import cn.szzsi.common.model.zshop.BusinessBalanceService;
import cn.szzsi.core.kit.UtilDate;
import cn.szzsi.interceptor.JSSDKInterceptor;
import cn.szzsi.interceptor.WechatLoginInterceptor;
import cn.szzsi.service.*;
import cn.szzsi.validator.OrderValidator;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.JFinal;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.JsTicket;
import com.jfinal.weixin.sdk.api.JsTicketApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.xpath.operations.Or;

import javax.servlet.http.Cookie;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 前台类 - 订单处理
 */
public class OrderController extends BaseWebController<Orders> {

	private Integer totalQuantity;// 商品总数
	private Integer totalPoint;// 总积分
	private Double totalWeightGram;// 商品总重量（单位：g）
	private BigDecimal productTotalPrice;// 总计商品价格
	private String memo;// 附言

	private List<CartItem> cartItemList;// 购物车项
	private DeliveryType deliveryType;// 配送方式
	private PaymentConfig paymentConfig;// 支付方式
	private PaymentType paymentType;// 支付类型
	private BigDecimal paymentFee;// 支付手续费
	private BigDecimal amountPayable;// 应付金额（不含支付费用）
	private Orders order;// 订单
	private Receiver receiver;
	private String uid;//商户id,也是用户的店铺id
	private Product product;
	private Page<Orders> pager;
	//商户相关资料
	private String appid;//应用ID
	private String secret;//应用密钥
	private String partner;//商户号
	private String key;//支付秘钥
	// 订单列表
	public void list(){
		int pageNumber = getParaToInt("pageNumber",1);
		int pageSize = getParaToInt("pageSize", Orders.DEFAULT_ORDER_LIST_PAGE_SIZE);
		
		Page<Orders> pager = Orders.dao.getOrderPager(pageNumber,pageSize,getLoginMember().getStr("id"));
		setAttr("pager", pager);
		setAttr("type",getPara("type","dfh"));
		wapTemplatePath("order_list.html");
		//getTemplatePath(uid,"order_list");//到这个方法里面打断点，path值就是存放视图的文件夹
	}

    //1.页面 订单列表异步加载
    public void orderListForm() {
		String type=getPara("type");
        setAttr("type", type);
        wapTemplatePath("order_list.html");

    }

    //2.加载数据
    public void ajaxOrderList() {
        int pageNumber = getParaToInt("pageNumber", 1);//第几页,默认1
        int pageSize = getParaToInt("pageSize", 10);//每页的数量,默认10
        uid = getPara("shopId");
        String type = getPara("type");
        if ("logistics".equals(type)) {
            List<Object> list = new ArrayList<Object>();
            renderJson(Msg.success(list));
        } else {
            List<Object> list = MemberOrderService.service.getOrdersByType(pageNumber, pageSize, getLoginMember().getStr("id"), type);
            renderJson(Msg.success(list));
        }
    }


    // 订单信息(从购物车进入)
    public void info() {
        uid = getPara("shopId");//用户的shopId对应商户的id(uid),商户的shopId为"0"
        Member member = getLoginMember();
        cartItemList = member.getCartItemList();
        productTotalPrice = new BigDecimal("0");
        for (CartItem cartItem : cartItemList) {
            Product product = cartItem.getProduct();
            if (product.getStore() != null && (cartItem.getQuantity() + product.getFreezeStore()) > product.getStore()) {
                renderHtml("<script>alert('商品库存不足，请返回修改!');history.go(-1);</script>");
                return;
            }
            productTotalPrice = product.getPreferentialPrice(member).multiply(new BigDecimal(cartItem.getQuantity())).add(productTotalPrice);
            productTotalPrice = SystemConfigUtil.getOrderScaleBigDecimal(productTotalPrice);//价格统一化
        }
        setAttr("loginMember", member);
        setAttr("productTotalPrice", productTotalPrice);
		setAttr("allPaymentConfig", PaymentConfig.dao.getAll());//支付方式
        setAttr("userBalance", member.getUserBalance());

        setAttr("cartItemList", cartItemList);
        String receiverId = getPara("receiverId");
        setAttr("receiverId", receiverId);
        if (StrKit.notBlank(receiverId)) {
            Receiver selecttReceiver = Receiver.dao.findById(receiverId);
            setAttr("selecttReceiver", selecttReceiver);
        }

		//判断浏览器类型,如果不是微信浏览器访问,支付方式列表不显示微信支付(因为公众号支付没有openid)
		String userAgent=getRequest().getHeader("user-agent").toLowerCase();//获取浏览器类型
		if(userAgent.indexOf("micromessenger")!=-1){//微信浏览器访问
			setAttr(CommonUtil.BROWSER_TYPE,"weixinBrowser");
		}
		wapTemplatePath("order_info.html");
	}
	// 订单保存
	@Before({OrderValidator.class, Tx.class})
	public void save() throws BusinessException {
		boolean isMinNi = getParaToBoolean("isMinNi", false);//是否是小程序
		totalQuantity = 0;
		Member member=getLoginMember();
		String paymentConfigId = getPara("paymentConfig_id","");
		memo = getPara("memo");
		receiver = getModel(Receiver.class);
		Integer paidPoints = getParaToInt("payPoints",0);
		BigDecimal paidDeposit = new BigDecimal(getPara("payDeposit", "0"));
		BigDecimal paidPointsAsDeposit = new BigDecimal(paidPoints).divide(new BigDecimal(100));
		/*if (paidPoints > 0 || paidDeposit.compareTo(new BigDecimal(0)) > 0){
			int updated = Db.update("UPDATE mall_user_balance SET balance = balance - ?, point = point - ? WHERE mid = ? AND balance >= ? AND point >= ?", paidDeposit, paidPoints, member.getId(), paidDeposit, paidPoints);
			if (updated != 1){
				addActionError("积分或余额不足");
				return;
			}
		}*/
        productTotalPrice = new BigDecimal("0");
        totalWeightGram = 0D;
		List<Product>productList=new ArrayList<>();
		cartItemList = member.getCartItemList();
        for (CartItem cartItem : cartItemList) {
            Product product = cartItem.getProduct();
			productList.add(product);
			if (product.getStore() != null && (cartItem.getQuantity() + product.getFreezeStore() > product.getStore())) {
				addActionError("商品[" + product.getName() + "]库存不足！");
				return;
			}
			if (product.getStore() != null) {
				product.set("freezeStore", product.getFreezeStore() + cartItem.getQuantity());
				if (product.getIsOutOfStock()) {
					product.getProductAttributeMapStore();
					HtmlService.service.productContentBuildHtml(product);
				}
				product.update();
			}

            Double weightGram = DeliveryType.toWeightGram(product.getWeight(), product.getWeightUnitValue());
            totalWeightGram = ArithUtil.add(totalWeightGram, ArithUtil.mul(weightGram, cartItem.getQuantity()));
            totalQuantity += cartItem.getQuantity();
			productTotalPrice = product.getPreferentialPrice(member).multiply(new BigDecimal(cartItem.getQuantity())).add(productTotalPrice);
			productTotalPrice = SystemConfigUtil.getOrderScaleBigDecimal(productTotalPrice);
			cartItem.delete();
        }
        //BigDecimal deliveryFee = deliveryType.getDeliveryFee(totalWeightGram);
        paymentConfig = PaymentConfig.dao.findById(paymentConfigId);//支付方式
		if (StrKit.notBlank(receiver.getId())) {
			receiver = Receiver.dao.findById(receiver.getId());//收货地址
		}
		String orderPlateFormId=StrKit.getRandomUUID();//平台总订单id
		//给商户分单(未支付订单)
		Map<String, List<Product>>listMap=convert(productList);
		BigDecimal allDeliveryFee=new BigDecimal(0);//所有商品运费(可能来自不同的商户)
		for (String shopId : listMap.keySet()) {
			List<Product>products=listMap.get(shopId);//商品所属的商户
			Double businessTotalWeightGram = 0D;//商户商品总重量
			Integer businessTotalQuantity=0;//商户商品总数量
			BigDecimal deliveryFee=new BigDecimal(0);//该商户的运费
			BigDecimal businessProductTotalPrice=new BigDecimal(0);//商户商品总价
			String businessOrderId=StrKit.getRandomUUID();
			for(Product product:products){
				Double weightGram = DeliveryType.toWeightGram(product.getWeight(), product.getWeightUnitValue());
				businessTotalWeightGram = ArithUtil.add(businessTotalWeightGram,weightGram);
				businessTotalQuantity+=1;
				businessProductTotalPrice = product.getPreferentialPrice(member).add(businessProductTotalPrice);
				OrderItemService.service.saveOrderItem(product, 1, businessOrderId, member);//商品项(商品明细列表)
			}
			deliveryType = DeliveryTypeService.service.getDeliverType(receiver, shopId);
			if(deliveryType!=null){
				deliveryFee = DeliveryTypeService.service.getDeliveryFee(Double.valueOf(businessTotalWeightGram), deliveryType);//计算运费(商户)
			}
			allDeliveryFee=allDeliveryFee.add(deliveryFee);//计算运费(所有商户运费)
			//创建商户订单
			order=OrderService.service.createBusinessOrder(businessOrderId,orderPlateFormId,deliveryType,businessProductTotalPrice,deliveryFee,businessTotalWeightGram,businessTotalQuantity,receiver,getPara("memo"),member,shopId,paymentConfig);
			OrderService.service.saveOrderLog(OrderLogType.create.ordinal(), order, "订单创建");// 订单日志
			//创建商户订单


		}
		paymentFee = paymentConfig.getBusinessPaymentFee(productTotalPrice.add(allDeliveryFee), paymentConfig);
		BigDecimal totalAmount = productTotalPrice.add(allDeliveryFee).add(paymentFee);//商品费用+配送费用+支付手续费
		// 待支付
		BigDecimal toPay = totalAmount.subtract(paidDeposit).subtract(paidPointsAsDeposit);
		int payStatus = toPay.compareTo(new BigDecimal(0));
		if (payStatus < 0){
			throw new BusinessException("用户错误");
		}
		//创建平台总订单
		OrdersPlateform ordersPlateform=OrderService.service.createPlateFormOrder(orderPlateFormId,totalQuantity,productTotalPrice,allDeliveryFee,paymentFee,paidDeposit,paidPoints,paidPointsAsDeposit,paymentConfig,member);
		OrderService.service.saveOrderLog(OrderLogType.create.ordinal(), ordersPlateform, "订单创建");// 订单日志
		//创建平台总订单


        //如果该订单用了余额或者积分支付,则添加余额支付明细
        /*if (order.getPaidDeposit().compareTo(new BigDecimal(0)) > 0) {
            UserBalanceDetailService.service.savePaymentInfo(member.getId(), order.getPaidDeposit(), UserBalanceDetail.BalanceType.memberPayment.ordinal(), member.getShopId(), order.getOrderSn());//支付明细
        }
        if (order.getPaidPoints() > 0) {
            UserPointDetailService.service.saveInfo(member.getId(), paidPoints, UserPointDetail.PointDetailType.memberPayment.ordinal(), "订单支付(积分抵扣)");//积分明细
        }*/
        //如果该订单用了余额或者积分支付,则添加余额支付明细
        //OrderService.service.saveOrderLog(OrderLogType.create.ordinal(), order, "订单创建");// 订单日志
        //将Cookie购物车总数量改为0
        Cookie quantity = new Cookie(CartItemCookie.CART_ITEM_LIST_COOKIE_TOTAL_QUANTITY, "0");
        quantity.setPath(getRequest().getContextPath() + "/");
        quantity.setMaxAge(CartItemCookie.CART_ITEM_LIST_COOKIE_MAX_AGE);
        getResponse().addCookie(quantity);
        //将Cookie购物车总数量改为0

        setAttr("ordersPlateform", ordersPlateform);
        setAttr("openId", member.getOpenid());
		setAttr("paymentFee", paymentFee);
		setAttr("paymentConfig", paymentConfig);
		if (paymentConfig.getPaymentConfigTypeValue() == PaymentConfig.PaymentConfigType.weixin) {//微信支付
			appid = _Config.p.get("wechat_appid");//应用ID
			secret = _Config.p.get("wechat_secret");//应用密钥
			WeixinConfig weixinConfig = new WeixinConfig();
			weixinConfig.setAppid(appid);
			weixinConfig.setSecret(secret);
			ApiConfigKit.setThreadLocalApiConfig(getApiConfig(weixinConfig));

			JsTicket jsApiTicket = JsTicketApi.getTicket(JsTicketApi.JsApiType.jsapi);
			String jsapi_ticket = jsApiTicket.getTicket();
			String nonce_str = create_nonce_str();
			// 注意 URL 一定要动态获取，不能 hardcode.
			String url = _Config.p.get("mall_web.url") + getRequest().getServletPath();
			String qs = getRequest().getQueryString(); // 参数
			if (qs != null) {
				url = url + "?" + (getRequest().getQueryString());
			}
			String timestamp = create_timestamp();
			// 这里参数的顺序要按照 key 值 ASCII 码升序排序,注意这里参数名必须全部小写，且必须有序
			String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
			String signature = HashKit.sha1(str);
			setAttr("appId", ApiConfigKit.getApiConfig().getAppId());
			setAttr("nonceStr", nonce_str);
			setAttr("timestamp", timestamp);
			setAttr("url", url);
			setAttr("signature", signature);
			setAttr("base", getRequest().getContextPath());
			setAttr("jsapi_ticket", jsapi_ticket);
			setAttr("openId", member.getOpenid());
		}
		if (isMinNi) {
			wapTemplatePath("openminniprogram.html");
		} else {
			wapTemplatePath("order_result.html");
		}
    }

	// 单个商品订单信息(单个商品-->点击立即购买)
	public void singleInfo() {
		Member member=getLoginMember();
		String productId=getPara("productId");
		Product product=Product.dao.findById(productId);//展示商品
		String specificationValueIds = getPara("specificationValueIds");//规格id
		if (StringUtils.isNotBlank(specificationValueIds)) {
			product = Product.getProductBySpecificationvalues(specificationValueIds, product.getSpecificationtype());
		}
		if (product.getInt("store") != null && (product.getInt("freezeStore")) > product.getInt("store")) {
			renderHtml("<script>alert('商品库存不足，请返回修改!');history.go(-1);;</script>");
			return;
		}
		totalQuantity = getParaToInt("totalQuantity",1);//购买数量
		totalWeightGram = 0D;
		productTotalPrice = new BigDecimal("0");//商品总价
		Double weightGram = DeliveryType.toWeightGram(product.getWeight(), product.getWeightUnitValue());
		totalWeightGram = ArithUtil.add(totalWeightGram, weightGram)*totalQuantity;//总重量
		productTotalPrice = product.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(totalQuantity)) ;//会员打折后的价格
		productTotalPrice = SystemConfigUtil.getOrderScaleBigDecimal(productTotalPrice);//转换格式
		setAttr("productId",productId);
		setAttr("product",product);
		setAttr("loginMember", member);
		setAttr("totalQuantity", totalQuantity);
		setAttr("totalWeightGram", totalWeightGram);
		setAttr("productTotalPrice", productTotalPrice);
		setAttr("allPaymentConfig", PaymentConfig.dao.getAll());//支付方式
		setAttr("userBalance", member.getUserBalance());
		String receiverId=getPara("receiverId");
		setAttr("receiverId",receiverId);
		if(StrKit.notBlank(receiverId)){
			Receiver selecttReceiver=Receiver.dao.findById(receiverId);
			setAttr("selecttReceiver",selecttReceiver);
		}
		//判断浏览器类型,如果不是微信浏览器访问,支付方式列表不显示微信支付(因为公众号支付没有openid)
		String userAgent=getRequest().getHeader("user-agent").toLowerCase();//获取浏览器类型
		if(userAgent.indexOf("micromessenger")!=-1){//微信浏览器访问
			setAttr(CommonUtil.BROWSER_TYPE,"weixinBrowser");
		}
		wapTemplatePath("order_info_single.html");
	}
	//立即购买保存订单
	@Before({Tx.class})
	public void singleSave() {
        boolean isMinNi = getParaToBoolean("isMinNi", false);//是否是小程序
		Member member=getLoginMember();
		String paymentConfig_id = getPara("paymentConfig_id");
		String productId=getPara("productId");
		if(StrKit.notBlank(productId)){//立即购买
			product=Product.dao.findById(productId);
		}
		Integer paidPoints = getParaToInt("payPoints",0);
		BigDecimal paidDeposit = new BigDecimal(getPara("payDeposit", "0"));
		BigDecimal paidPointsAsDeposit = new BigDecimal(paidPoints).divide(new BigDecimal(100));
		/*if (paidPoints > 0 || paidDeposit.compareTo(new BigDecimal(0)) > 0){
			int updated = Db.update("UPDATE mall_user_balance SET balance = balance - ?, point = point - ? WHERE mid = ? AND balance >= ? AND point >= ?", paidDeposit, paidPoints, member.getId(), paidDeposit, paidPoints);
			if (updated != 1){
				addActionError("积分或余额不足");
				return;
			}
		}*/
		receiver = getModel(Receiver.class);
		if (StrKit.notBlank(receiver.getId())) {
			receiver = Receiver.dao.findById(receiver.getId());
		}
		if (product.getStore() != null && (product.getFreezeStore()+1 > product.getStore())) {
			addActionError("商品[" + product.getStr("name") + "]库存不足！");
			return;
		}
		deliveryType = DeliveryTypeService.service.getDeliverType(receiver,uid);
		totalQuantity = getParaToInt("totalQuantity");//购买数量
		if(totalQuantity==null){
			totalQuantity=1;
		}

		totalWeightGram = 0D;
		productTotalPrice = new BigDecimal("0");
		productTotalPrice = product.getPreferentialPrice(member).multiply(new BigDecimal(totalQuantity));//格式化之前价格
		productTotalPrice = SystemConfigUtil.getOrderScaleBigDecimal(productTotalPrice);//格式化后价格
		Double weightGram = DeliveryType.toWeightGram(product.getWeight(), product.getWeightUnitValue());//单个商品重量
		totalWeightGram = ArithUtil.add(totalWeightGram, weightGram)*totalQuantity;//总重量
		BigDecimal deliveryFee = deliveryType.getDeliveryFee(totalWeightGram);
		paymentConfig = PaymentConfig.dao.findById(paymentConfig_id);
		paymentFee = paymentConfig.getBusinessPaymentFee(productTotalPrice.add(deliveryFee),paymentConfig);//支付手续费
		if(paymentConfig.getPaymentConfigTypeValue() == PaymentConfig.PaymentConfigType.weixin){//微信支付,要初始化参数
			appid=_Config.p.get("wechat_appid");;//应用ID
			secret=_Config.p.get("wechat_secret");//应用密钥
			WeixinConfig weixinConfig=new WeixinConfig();
			weixinConfig.setAppid(appid);
			weixinConfig.setSecret(secret);
			ApiConfigKit.setThreadLocalApiConfig(getApiConfig(weixinConfig));

			JsTicket jsApiTicket = JsTicketApi.getTicket(JsTicketApi.JsApiType.jsapi);
			String jsapi_ticket = jsApiTicket.getTicket();
			String nonce_str = create_nonce_str();
			// 注意 URL 一定要动态获取，不能 hardcode.
			String url=_Config.p.get("mall_web.url")+getRequest().getServletPath();
			String qs = getRequest().getQueryString(); // 参数
			if (qs != null) {
				url = url + "?" + (getRequest().getQueryString());
			}
			String timestamp = create_timestamp();
			String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
			String signature = HashKit.sha1(str);
			setAttr("appId", ApiConfigKit.getApiConfig().getAppId());
			setAttr("nonceStr", nonce_str);
			setAttr("timestamp", timestamp);
			setAttr("url", url);
			setAttr("signature", signature);
			setAttr("base", getRequest().getContextPath());
			setAttr("jsapi_ticket", jsapi_ticket);
			setAttr("openId",member.getOpenid());
		}
		BigDecimal totalAmount = productTotalPrice.add(deliveryFee).add(paymentFee);//商品费用+配送费用+支付手续费
		BigDecimal toPay = totalAmount.subtract(paidDeposit).subtract(paidPointsAsDeposit);//支付给第三方金额
		int payStatus = toPay.compareTo(new BigDecimal(0));
		if (payStatus < 0){
			addActionError("积分或余额使用错误！");
			return;
		}
		//创建平台总订单
		String orderPlateFormId=StrKit.getRandomUUID();
		OrdersPlateform ordersPlateform=OrderService.service.createPlateFormOrder(orderPlateFormId,totalQuantity,productTotalPrice,deliveryFee,paymentFee,paidDeposit,paidPoints,paidPointsAsDeposit,paymentConfig,member);
		//保存商户订单
		order=OrderService.service.createBusinessOrder(StrKit.getRandomUUID(),orderPlateFormId,deliveryType,productTotalPrice,deliveryFee,totalWeightGram,totalQuantity,receiver,getPara("memo"),member,product.getUid(),paymentConfig);
		//如果该订单用了余额或者积分支付,则添加余额支付明细
		/*if(order.getPaidDeposit().compareTo(new BigDecimal(0))>0){
			UserBalanceDetailService.service.savePaymentInfo(member.getId(),order.getPaidDeposit(), UserBalanceDetail.BalanceType.memberPayment.ordinal(),member.getShopId(),order.getOrderSn());//支付明细
		}
		if(order.getPaidPoints()>0){
			UserPointDetailService.service.saveInfo(member.getId(),paidPoints, UserPointDetail.PointDetailType.memberPayment.ordinal(),"订单支付(积分抵扣)");//积分明细
		}*/
		//如果该订单用了余额或者积分支付,则添加余额支付明细
		OrderItemService.service.saveOrderItem(product,totalQuantity,order.getId(),member);// 商品项
		if (product.getStore() != null) {
			product.setFreezeStore(product.getFreezeStore()+totalQuantity);
			if (product.getIsOutOfStock()) {
				product.getProductAttributeMapStore();
			}
			product.update();
			if (product.getIsOutOfStock()) {
				HtmlService.service.productContentBuildHtml(product);
			}
		}

		// 订单日志
		OrderService.service.saveOrderLog(OrderLogType.create.ordinal(),order,"订单创建");
		setAttr("ordersPlateform", ordersPlateform);
		setAttr("paymentFee", paymentFee);
		setAttr("paymentConfig", paymentConfig);
		setAttr("productId",productId);
		setAttr("openId",member.getOpenid());
		setAttr("orderPlateFormId",orderPlateFormId);
        if (isMinNi) {
            wapTemplatePath("openminniprogram.html");
        } else {
            wapTemplatePath("order_result.html");
        }
	}


    // 订单详情
    public void view() {
        id = getPara("id", "");
        order = Orders.dao.findById(id);

        totalPoint = 0;
        if (getSystemConfig().getPointType() == PointType.productSet) {
            for (OrderItem orderItem : order.getOrderItemList()) {
                totalPoint = orderItem.getProduct().getInt("point") * orderItem.getInt("productQuantity") + totalPoint;
            }
        } else if (getSystemConfig().getPointType() == PointType.orderAmount) {
            totalPoint = order.getBigDecimal("productTotalPrice").multiply(new BigDecimal(getSystemConfig().getPointScale().toString())).setScale(0, RoundingMode.DOWN).intValue();
        }
        setAttr("order", order);
		wapTemplatePath("order_view.html");
        //getTemplatePath(uid, "order_view");

    }

    //买家申请退款
    public void applyRefund() {
        String id = getPara("id");
        order = Orders.dao.findById(id);
        order.set("paymentStatus", Orders.PaymentStatus.inRefund.ordinal());//支付状态改为申请退款中
        order.update();

        // 订单日志
        OrderService.service.saveOrderLog(OrderLog.OrderLogType.refund.ordinal(), order, "买家申请退货款");

        Map<String, String> jsonMap = new HashMap<String, String>();
        jsonMap.put(STATUS, SUCCESS);
        jsonMap.put(MESSAGE, "操作成功！");
        renderJson(jsonMap);

    }

    //买家确认收货
    @Before(Tx.class)
    public void sureReceipt() {
        final String orderId = getPara("id");
        if (StrKit.isBlank(orderId)) {
            ajaxJsonWarnMessage("订单ID不能空！");
            return;
        }
        order = Orders.dao.findById(orderId);
        if (order.getOrderStatusValue() == Orders.OrderStatus.completed) {
            ajaxJsonWarnMessage("此订单已经完成！");
        } else if (order.getOrderStatusValue() == Orders.OrderStatus.invalid) {
            ajaxJsonErrorMessage("此订单已经作废！");
        } else {
            order.set("orderStatus", Orders.OrderStatus.valueOf(Orders.OrderStatus.completed.name()).ordinal());
            updated(order);
            OrderService.service.saveOrderLog(OrderLog.OrderLogType.completed.ordinal(), order, "买家确认收货");// 订单日志

			//买家确认收货,执行分销处理
			_Config.fixedThreadPool.execute(new Runnable() {
				@Override
				public void run() {//执行分销处理
					try {
						Member member=Member.dao.findById(order.getMemberId());

						FenxiaoService.service.fenxiaoHandle(member,order);//分销给推荐人
						OrderService.service.productBackMoney(order,member);//购物返现
						AgentRecommendBusinessService.service.orderBackMoneyToAgent(order);//给推荐代理商返现

						BusinessBalanceService.service.updateBalance(order.getUid(),order.getTotalAmount());//给卖家充值
						BusinessBalanceDetailService.service.saveInfo(order.getUid(),order.getTotalAmount(),1,order.getOrderSn(),order.getMemberId(),"会员确认收货");
					} catch (BusinessException e) {
						e.printStackTrace();
					}
				}
			});
            ajaxJsonSuccessMessage("您的操作已成功！");
        }
    }

    //买家申请退货
    public void applyReshiped() {
        String id = getPara("id");
        order = Orders.dao.findById(id);
        order.set("shippingStatus", Orders.ShippingStatus.inReshiped.ordinal());//支付状态改为申请退款中
        order.update();

        // 订单日志
        OrderService.service.saveOrderLog(OrderLog.OrderLogType.reship.ordinal(), order, "买家申请退货");

        Map<String, String> jsonMap = new HashMap<String, String>();
        jsonMap.put(STATUS, SUCCESS);
        jsonMap.put(MESSAGE, "操作成功！");
        renderJson(jsonMap);

    }

    //买家评价
    @Before(JSSDKInterceptor.class)
    public void evaluateEdit() {
        uid = getPara("shopId");//用户的shopId对应商户的id(uid),商户的shopId为"-1"
        SiteConfig siteConfig = SiteConfig.getByShopId(uid);
        String shopAlias = siteConfig.getStr("shopAlias");
        setAttr("siteConfig", siteConfig);
        setAttr("shopAlias", shopAlias);
        setAttr("shopId", uid);
        id = getPara("id", "");
        order = Orders.dao.findById(id);
        setAttr("order", order);
        setAttr("base", getRequest().getContextPath());
        getTemplatePath(uid, "order_evaluate");
    }

    //保存买家评论
    public void evaluateSave() {
        String type = getPara("type");
        String orderId = getPara("orderId");
        Member member = getLoginMember();
        String memberId = member.getStr("id");
        uid = member.getStr("shopId");
        String content = getPara("content", "好评!");//默认好评
        String imageStror = getPara("imageStr");
        String productId = getPara("productId");
        Integer countStar = getParaToInt("countStar");//星级评分
        ProductEvaluate.saveEvaluate(productId, content, imageStror, countStar, memberId, uid);
        OrderItem orderItem = OrderItem.dao.getByOrderIdAndProductId(orderId, productId);
        if (orderItem != null) {
            orderItem.set("isEvaluate", Orders.OrderEvaluate.alreadyevaluate.ordinal()).update();//已评价
        }
        List<OrderItem> orderItemList = OrderItem.dao.getByOrderIdAndStatus(orderId, Orders.OrderEvaluate.notevaluate.ordinal());
        if (orderItemList.size() == 0) {
            //如果订单全部评价,将订单状态改为已评价
            Orders.dao.findById(orderId).set("orderEvaluate", Orders.OrderEvaluate.alreadyevaluate.ordinal()).update();
        }
        //查询该订单的商品是否已经全部评价,若是,则将订单状态改为已评价


        renderJson(Msg.SUCCESS);
    }

    public void evaluateimage() {
        String type = getPara("type");
        Map<String, String> map = new HashMap<String, String>();
        if ("wx".equals(type)) {
            String shopId = getPara("shopId");
            String serverId = getPara("serverId");//微信服务器文件id
            SiteConfig siteConfig = SiteConfig.getByShopId(shopId);
            /*String appid=siteConfig.getStr("appid");
            String secret=siteConfig.getStr("secret");
			String apiid=siteConfig.getStr("apiid");*/

            String access_token = WeixinUtil.getAccessToken(shopId);
            String imageWeixinUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + access_token + "&media_id=" + serverId;
            String filename = QRCodeUtil.savePic(imageWeixinUrl, UtilDate.getOrderNum() + "evaluate.png", JFinal.me().getServletContext().getRealPath("/upload/evaluate"));
            int start = filename.indexOf("/upload");
            String imagePath = filename.substring(start);
            map.put("imageurl", imagePath);
            map.put("random", CommonUtil.getUUID());
            map.put("code", "0");

            //获取accessToken
		/*String param="apiid="+apiid;
		String reqUrl= ReqUrlUtil.getAccessToken;
		String result= HttpKit.post(reqUrl,null,param);
		JSONObject obj = new JSONObject(result);
		String access_token=obj.getJSONObject("data").get("access_token").toString();

		String imageWeixinUrl="https://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+access_token+"&media_id="+serverId;
		System.out.println("imageWeixinUrl-----------------"+imageWeixinUrl);
		String filename = QRCodeUtil.savePic(imageWeixinUrl,UtilDate.getOrderNum()+"evaluate.png",JFinal.me().getServletContext().getRealPath("/upload/evaluate/"));*/
        } else {
            UploadFile uploadFile = getFile("evaluateimage");
            String imageurl = "";
            if (uploadFile != null) {
                imageurl = _Config.p.get("file.url") + uploadFile.getFileName();//网店logo路径
            }
            map.put("imageurl", imageurl);
            map.put("random", CommonUtil.getUUID());
        }
        renderJson(map);

    }

    @Clear
    public void deleteWebImage() {
        renderJson(Msg.SUCCESS);

    }

	// 支付确认
	public void confirm() {
        boolean isMinNi =getParaToBoolean("isMinNi",false);
        String orderId=getPara("order.id");
        Orders order=Orders.dao.findById(orderId);
        OrdersPlateform ordersPlateform=OrdersPlateform.dao.findById(order.getParentId());
		setAttr("ordersPlateform",ordersPlateform);
        if (isMinNi) {
            wapTemplatePath("openminniprogram.html");
        } else {
        	//wapTemplatePath("");
			wapTemplatePath("order_result.html");
        }

    }

    public ApiConfig getApiConfig(WeixinConfig weixinConfig) {
        ApiConfig ac = new ApiConfig();
        // 配置微信 API 相关常量
        //ac.setToken(AConfig.p.get("token"));
        ac.setAppId(weixinConfig.getAppid());
        ac.setAppSecret(weixinConfig.getSecret());

        /**
         * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
         * 2：false采用明文模式，同时也支持混合模式
         */
        ac.setEncryptMessage(_Config.p.getBoolean("encryptMessage", false));
        ac.setEncodingAesKey(_Config.p.get("encodingAesKey",
                "setting it in config file"));
        return ac;
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }


    //展示物流信息
    public void getLogisticsInfo() {
        String orderId = getPara("id", "");//订单id
        uid = getPara("shopId");//用户的shopId对应商户的id(uid),商户的shopId为"-1"
        Record record = Db.findFirst("select deliveryCorpName,deliverySn from mall_shipping where order_id = ?", orderId);
        if (record != null) {
            String deliverySn = record.getStr("deliverySn");//物流单号
            try {
                JSONObject jsonObject = KdApiOrderDistinguish.getOrderTraces(deliverySn);
                if (jsonObject == null) {
                    setAttr("shipperName", record.getStr("deliveryCorpName"));
                    setAttr("logisticCode", record.getStr("deliverySn"));
                    setAttr("reason", "该订单未关联物流信息！");
                } else {
                    if ("0".equals(jsonObject.getString("State"))) {//无轨迹\
                        setAttr("reason", jsonObject.get("Reason"));
                        setAttr("shipperName", record.getStr("deliveryCorpName"));
                        setAttr("logisticCode", record.getStr("deliverySn"));
                    } else {
                        setAttr("traces", jsonObject.get("Traces"));
                        setAttr("shipperName", jsonObject.getString("ShipperName"));
                        setAttr("logisticCode", jsonObject.getString("LogisticCode"));
                    }
                }

                getTemplatePath(uid, "order_logistics");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            setAttr("reason", "该订单未关联物流信息！");
            getTemplatePath(uid, "order_logistics");
        }

    }

    /**
     * 获取配送费用
     */
    public void getDeliveryFee() {
        String shopId = getPara("shopId");//店铺id
        String totalWeightGram = getPara("totalWeightGram");//商品总重量
        String receiverId = getPara("receiverId");//收货地区id
        Receiver receiver = Receiver.dao.findById(receiverId);//收货地址实体类
        Integer provinceId = receiver.getProvinceId();//省id
        Integer cityId = receiver.getCityId();//市id
        Integer areaId = receiver.getAreaId();//区id
        String allAreaId = provinceId + "," + cityId + "," + areaId + ",0";
        DeliveryAreaRelation deliveryAreaRelation = DeliveryAreaRelation.dao.findFirst("select * from mall_delivery_area_relation where shopId=? and areaId in (" + allAreaId + ")", shopId);
        if (deliveryAreaRelation != null) {//用户的收货地区在商户所设置的模板中
            //1.查看运费模板
            DeliveryType deliveryType = DeliveryType.dao.findById(deliveryAreaRelation.getDeliveryTypeId());
            //2.计算运费
            BigDecimal deliveryFee = DeliveryTypeService.service.getDeliveryFee(Double.valueOf(totalWeightGram), deliveryType);
            renderJson(Ret.ok("deliveryFee", deliveryFee + ""));
        } else {//用户的收货地区不在商户所设置的模板中,将运费置为0
            renderJson(Ret.ok("deliveryFee", "0.00"));
        }

    }

    public void getAllDeliverFee(){
		Member member = getLoginMember();
		String receiverId = getPara("receiverId");//收货地区id
		Receiver receiver = Receiver.dao.findById(receiverId);//收货地址实体类
		Integer provinceId = receiver.getProvinceId();//省id
		Integer cityId = receiver.getCityId();//市id
		Integer areaId = receiver.getAreaId();//区id
		String allAreaId = provinceId + "," + cityId + "," + areaId + ",0";

		List<Product>productList=new ArrayList<>();
		cartItemList = member.getCartItemList();
		for (CartItem cartItem : cartItemList) {
			Product product = cartItem.getProduct();
			productList.add(product);
		}
		Map<String, List<Product>>listMap=convert(productList);
		BigDecimal allDeliveryFee=new BigDecimal(0);
		for (String shopId : listMap.keySet()) {
			List<Product>products=listMap.get(shopId);
			totalWeightGram = 0D;
			for(Product product:products){
				Double weightGram = DeliveryType.toWeightGram(product.getWeight(), product.getWeightUnitValue());
				totalWeightGram = ArithUtil.add(totalWeightGram,weightGram);
			}
			DeliveryAreaRelation deliveryAreaRelation = DeliveryAreaRelation.dao.findFirst("select * from mall_delivery_area_relation where shopId=? and areaId in (" + allAreaId + ")", shopId);
			if(deliveryAreaRelation!=null){
				//1.查看运费模板
				DeliveryType deliveryType = DeliveryType.dao.findById(deliveryAreaRelation.getDeliveryTypeId());
				//2.计算运费
				BigDecimal deliveryFee = DeliveryTypeService.service.getDeliveryFee(Double.valueOf(totalWeightGram), deliveryType);
				allDeliveryFee=allDeliveryFee.add(deliveryFee);
			}else{
				allDeliveryFee=allDeliveryFee.add(new BigDecimal(0));
			}
		}
		System.out.println("allDeliveryFee------------"+allDeliveryFee);
		renderJson(Ret.ok("deliveryFee", allDeliveryFee));
	}

	public static Map<String, List<Product>> convert(List<Product> products) {
		Map<String, List<Product>> converted = new LinkedHashMap<>();

		for (Product p : products){
			List<Product> shopProducts = converted.get(p.getUid());
			if (shopProducts == null){
				shopProducts = new ArrayList<>();
				converted.put(p.getUid(), shopProducts);
			}
			shopProducts.add(p);
		}
		//System.out.println("converted-----"+converted);
		return converted;
	}


}
